package com.specialtreasure.freightdepot.activity;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.app.core.activity.BaseNewActivity;
import com.app.core.config.Constants;
import com.app.core.config.HttpApi;
import com.app.core.util.UserUtils;
import com.specialtreasure.freightdepot.R;
import com.specialtreasure.freightdepot.model.Address;
import com.specialtreasure.freightdepot.model.BaseModel;
import com.specialtreasure.freightdepot.model.CUsers;
import com.specialtreasure.freightdepot.popupwindow.SelectCityPW;
import com.specialtreasure.freightdepot.popupwindow.SelectUnitPW;
import com.yanzhenjie.httpmodule.http.CallServer;
import com.yanzhenjie.httpmodule.http.Result;
import com.yanzhenjie.httpmodule.http.StringRequest;
import com.yanzhenjie.nohttp.Logger;
import com.yanzhenjie.nohttp.RequestMethod;
import com.yanzhenjie.nohttp.rest.CacheMode;
import com.yanzhenjie.nohttp.rest.Response;
import com.yanzhenjie.nohttp.rest.SimpleResponseListener;

import org.simple.eventbus.EventBus;

/**
 * Created by Administrator on 2017/8/23 0023.
 * 添加车辆
 */

public class AddCarActivity extends BaseNewActivity implements View.OnClickListener {
    public static final String TAG = "AddCarActivity";
    private ImageView iv_back;
    private EditText et_account;
    private EditText et_pwd;
    private EditText et_name;
    private EditText et_tel;
    private TextView tv_car_group;
    private TextView tv_title;
    private RelativeLayout rl_car_group;
    private TextView tv_car_length;
    private RelativeLayout rl_car_length;
    private TextView tv_car_type;
    private RelativeLayout rl_car_type;
    private EditText et_city;
    private EditText et_car_num;
    private TextView tv_home;
    private RelativeLayout rl_home;
    private EditText et_remark;
    private CheckBox ck_sms;
    private Button btn_save_add;
    private Button btn_save_cancel;
    private Button btn_cancel;
    private LinearLayout ll_root;

    String carLength;
    String carType;
    String belong_area;//归属地
    Integer group;
    Integer isSendMsg = 0;//(0.否 1.是)

    boolean isSaveAdd;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.act_add_car);
        initView();
        setData();
    }

    private void initView() {
        iv_back = (ImageView) findViewById(R.id.iv_back);
        et_account = (EditText) findViewById(R.id.et_account);
        et_pwd = (EditText) findViewById(R.id.et_pwd);
        et_name = (EditText) findViewById(R.id.et_name);
        et_tel = (EditText) findViewById(R.id.et_tel);
        tv_car_group = (TextView) findViewById(R.id.tv_car_group);
        rl_car_group = (RelativeLayout) findViewById(R.id.rl_car_group);
        tv_car_length = (TextView) findViewById(R.id.tv_car_length);
        rl_car_length = (RelativeLayout) findViewById(R.id.rl_car_length);
        tv_car_type = (TextView) findViewById(R.id.tv_car_type);
        rl_car_type = (RelativeLayout) findViewById(R.id.rl_car_type);
        et_city = (EditText) findViewById(R.id.et_city);
        et_car_num = (EditText) findViewById(R.id.et_car_num);
        tv_home = (TextView) findViewById(R.id.tv_home);
        rl_home = (RelativeLayout) findViewById(R.id.rl_home);
        et_remark = (EditText) findViewById(R.id.et_remark);
        ck_sms = (CheckBox) findViewById(R.id.ck_sms);
        btn_save_add = (Button) findViewById(R.id.btn_save_add);
        btn_save_cancel = (Button) findViewById(R.id.btn_save_cancel);
        btn_cancel = (Button) findViewById(R.id.btn_cancel);
        ll_root = (LinearLayout) findViewById(R.id.ll_root);
        tv_title = (TextView) findViewById(R.id.tv_title);

        iv_back.setOnClickListener(this);
        btn_save_add.setOnClickListener(this);
        btn_save_cancel.setOnClickListener(this);
        btn_cancel.setOnClickListener(this);
        rl_car_group.setOnClickListener(this);
        rl_car_length.setOnClickListener(this);
        rl_car_type.setOnClickListener(this);
        rl_home.setOnClickListener(this);

    }

    private void setData() {
        show(iv_back);
        tv_title.setText("添加车辆");

        //监听
        et_account.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View view, boolean b) {
                if (!b) {
                    if (et_account.getText().toString().trim().length() == 11) {
                        showDialog(Constants.LOADING);
                        checkPhone();
                    }
                }
            }
        });

    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_back://返回
            case R.id.btn_cancel:
                finish();
                break;
            case R.id.btn_save_add://保存继续添加
                isSaveAdd = false;
                submit();
                break;
            case R.id.btn_save_cancel://保存并退出
                isSaveAdd = true;
                submit();
                break;
            case R.id.rl_car_length://车长
                SelectUnitPW supw = new SelectUnitPW(this, "chechang.xml", "车长");
                supw.showAtBottom(ll_root);
                supw.setOnResultListener(new SelectUnitPW.OnResultListener() {
                    @Override
                    public void onResult(String str) {
                        if (!TextUtils.isEmpty(str)) {
                            tv_car_length.setText(str);
                            carLength = str;
                        }
                    }
                });

                break;
            case R.id.rl_car_type://车型
                SelectUnitPW supw1 = new SelectUnitPW(this, "chexing.xml", "车型");
                supw1.showAtBottom(ll_root);
                supw1.setOnResultListener(new SelectUnitPW.OnResultListener() {
                    @Override
                    public void onResult(String str) {
                        if (!TextUtils.isEmpty(str)) {
                            tv_car_type.setText(str);
                            carType = str;
                        }
                    }
                });

                break;
            case R.id.rl_home://归属地
                SelectCityPW pwTo = new SelectCityPW(this);
                pwTo.showAtBottom(ll_root);
                pwTo.setOnResultListener(new SelectCityPW.OnResultListener() {
                    @Override
                    public void onResult(Address address) {
                        if (address != null) {
                            belong_area = address.province + address.city + address.region;

                            //判断位置
                            if (address.province.equals(address.city)){
                                belong_area = address.city + address.region;
                            }

                            tv_home.setText(belong_area);
                        }
                    }

                });

                break;
            case R.id.rl_car_group://分组
                SelectUnitPW supw8 = new SelectUnitPW(this, "fenzu_two.xml", "分组");
                supw8.showAtBottom(ll_root);
                supw8.setOnResultListener(new SelectUnitPW.OnResultListener() {
                    @Override
                    public void onResult(String str) {
                        if (!TextUtils.isEmpty(str)) {
                            tv_car_group.setText(str);
                            if (str.equals("自有")) {
                                group = 0;
                            } else {
                                group = 1;
                            }

                        }
                    }
                });
                break;
        }

    }

    private void submit() {
        // validate
        String account = et_account.getText().toString().trim();
        if (TextUtils.isEmpty(account)) {
            Toast.makeText(this, "账号不能为空", Toast.LENGTH_SHORT).show();
            return;
        }

        String pwd = et_pwd.getText().toString().trim();
        if (TextUtils.isEmpty(pwd)) {
            Toast.makeText(this, "密码不能为空", Toast.LENGTH_SHORT).show();
            return;
        }

        String name = et_name.getText().toString().trim();
        if (TextUtils.isEmpty(name)) {
            Toast.makeText(this, "姓名不能为空", Toast.LENGTH_SHORT).show();
            return;
        }

        String tel = et_tel.getText().toString().trim();
        if (TextUtils.isEmpty(tel)) {
            Toast.makeText(this, "随车电话不能为空", Toast.LENGTH_SHORT).show();
            return;
        }

        String city = et_city.getText().toString().trim();
        if (TextUtils.isEmpty(city)) {
            Toast.makeText(this, "常跑城市不能为空", Toast.LENGTH_SHORT).show();
            return;
        }

        if (group == null) {
            Toast.makeText(this, "分组不能为空", Toast.LENGTH_SHORT).show();
            return;
        }

        if (carLength == null) {
            Toast.makeText(this, "车长不能为空", Toast.LENGTH_SHORT).show();
            return;
        }

        if (carType == null) {
            Toast.makeText(this, "车型不能为空", Toast.LENGTH_SHORT).show();
            return;
        }


        // TODO validate success, do something
        showDialog(Constants.LOADING);
        getData();
    }

    /**
     * 网络请求
     */
    private void getData() {
        String url = Constants.HTTP_URL + HttpApi.REGISTERCUSER;
        StringRequest request = new StringRequest(url, RequestMethod.POST);
        request.add("token", UserUtils.getToken());
        request.addNull("group", group);
        if (ck_sms.isChecked()) {
            isSendMsg = 1;
        } else {
            isSendMsg = 0;
        }
        request.addNull("isSendMsg", isSendMsg);
        request.addNull("username", et_account.getText().toString().trim());
        request.addNull("password", et_pwd.getText().toString().trim());
        request.addNull("certName", et_name.getText().toString().trim());
        request.addNull("phone", et_tel.getText().toString().trim());
        request.addNull("carNumber", et_car_num.getText().toString().trim());
        request.addNull("remark", et_remark.getText().toString().trim());
        request.addNull("runningRoute", et_city.getText().toString().trim());

        request.addNull("carLength", carLength);
        request.addNull("carType", carType);
        request.addNull("belong_area", belong_area);

        request.setCacheMode(CacheMode.ONLY_REQUEST_NETWORK);
        CallServer.getInstance().request(Constants.ZERO, request, new SimpleResponseListener<Result<String>>() {
            @Override
            public void onSucceed(int what, Response<Result<String>> response) {
                super.onSucceed(what, response);
                closeDialog();

                String result = response.get().getResult();
                Logger.e("请求成功：" + result);
                BaseModel baseModel = JSON.parseObject(result, BaseModel.class);
                if (baseModel != null) {
                    Integer status = baseModel.getStatus();
                    String msg = baseModel.getMsg();
                    if (status != null && status == 0) {
                        Toast.makeText(mContext, "添加车辆信息成功", Toast.LENGTH_SHORT).show();
                        EventBus.getDefault().post(new BaseModel(), Constants.UPDATEMETO);

                        if (isSaveAdd) {//保存并退出
                            finish();
                        } else {
                            clearText();
                        }

                    } else {
                        Toast.makeText(mContext, msg, Toast.LENGTH_SHORT).show();
                    }
                }


            }
        });

    }

    /**
     * 检测我的手机号
     */
    private void checkPhone() {
        String url = Constants.HTTP_URL + HttpApi.SELECTCUSERBYUSERNAME;
        StringRequest request = new StringRequest(url, RequestMethod.POST);
        request.add("token", UserUtils.getToken());
        request.add("username", et_account.getText().toString().trim());

        request.setCacheMode(CacheMode.ONLY_REQUEST_NETWORK);
        CallServer.getInstance().request(Constants.ZERO, request, new SimpleResponseListener<Result<String>>() {
            @Override
            public void onSucceed(int what, Response<Result<String>> response) {
                super.onSucceed(what, response);
                closeDialog();

                String result = response.get().getResult();
                Logger.e("请求成功：" + result);
                JSONObject jsonObject = JSON.parseObject(result);
                if (jsonObject != null) {
                    Integer status = jsonObject.getInteger("status");
                    String msg = jsonObject.getString("msg");

                    if (status != null && status == 0) {
                        CUsers data = JSON.parseObject(jsonObject.getJSONObject("data").toString(), CUsers.class);
                        if (data != null) {
                            et_city.setText(data.getRunningRoute());
                            et_tel.setText(data.getPhone());
                            et_name.setText(data.getCertName());
                            et_account.setText(data.getUsername());
                            et_car_num.setText(data.getCarNumber());
                            et_remark.setText(data.getRemark());
                            et_pwd.setText(data.getPassword());

                            tv_car_length.setText(data.getCarLength());
                            tv_car_type.setText(data.getCarType());
                            tv_home.setText(data.getBelongArea());


                            carLength=data.getCarLength();
                            carType=data.getCarType();
                            belong_area=data.getBelongArea();


                            if (!TextUtils.isEmpty(data.getRunningRoute())){
                                et_city.setFocusable(false);
                                et_city.setFocusableInTouchMode(false);
                            }
                            if (!TextUtils.isEmpty(data.getPhone())){
                                et_tel.setFocusable(false);
                                et_tel.setFocusableInTouchMode(false);
                            }
                            if (!TextUtils.isEmpty(data.getCertName())){
                                et_name.setFocusable(false);
                                et_name.setFocusableInTouchMode(false);
                            }
                            if (!TextUtils.isEmpty(data.getUsername())){
                                et_account.setFocusable(false);
                                et_account.setFocusableInTouchMode(false);
                            }
                            if (!TextUtils.isEmpty(data.getCarNumber())){
                                et_car_num.setFocusable(false);
                                et_car_num.setFocusableInTouchMode(false);
                            }
                            if (!TextUtils.isEmpty(data.getRemark())){
                                et_remark.setFocusable(false);
                                et_remark.setFocusableInTouchMode(false);
                            }
                            if (!TextUtils.isEmpty(data.getPassword())){
                                et_pwd.setFocusable(false);
                                et_pwd.setFocusableInTouchMode(false);
                            }

                            if (!TextUtils.isEmpty(data.getCarLength())){
                                rl_car_length.setOnClickListener(null);
                            }
                            if (!TextUtils.isEmpty(data.getCarType())){
                                rl_car_type.setOnClickListener(null);
                            }
                            if (!TextUtils.isEmpty(data.getBelongArea())){
                                rl_home.setOnClickListener(null);
                            }





                        }


                    } else {
//                        Toast.makeText(mContext, msg, Toast.LENGTH_SHORT).show();

                    }


                }


            }
        });
    }


    /**
     * 清空文本
     */
    private void clearText() {
        et_city.getText().clear();
        et_tel.getText().clear();
        et_name.getText().clear();
        et_account.getText().clear();
        et_car_num.getText().clear();
        et_remark.getText().clear();
        et_pwd.getText().clear();

        tv_car_group.setText("");
        tv_car_length.setText("");
        tv_car_type.setText("");
        tv_home.setText("");

    }


    @Override
    public String getActiviyName() {
        return TAG;
    }
}
